package com.hzncc.flowable_diboot.coderule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.service.impl.BaseServiceImpl;
import com.diboot.core.util.S;
import com.hzncc.flowable_diboot.coderule.entity.CodeRule;
import com.hzncc.flowable_diboot.coderule.service.CodeRuleService;
import com.hzncc.flowable_diboot.mapper.CodeRuleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
* 编码规则 相关Service实现类
* @author MyName
* @version 1.0
* @date 2024-06-28
* Copyright © MyCorp
*/
@Slf4j
@Service
public class CodeRuleServiceImpl extends BaseServiceImpl<CodeRuleMapper, CodeRule> implements CodeRuleService {

    @Transactional
    @Override
    public synchronized List<String> generateCode(String ruleCode, int i) {
        QueryWrapper<CodeRule> qw = new QueryWrapper<>();
        qw.eq("code", ruleCode);
        CodeRule rule = getSingleEntity(qw);
        if (rule == null) {
            throw new RuntimeException(ruleCode+" 规则不存在");
        }
        List<String> result = new ArrayList<>();
        for (int j = 0; j < i; j++) {
            String code = buildCode(rule);
            result.add(code);
        }
        updateEntity(rule);
        return result;
    }

    @Override
    public String generateCode(String ruleCode) {
        return generateCode(ruleCode,1).get(0);
    }

    private String buildCode(CodeRule codeRule){
        String prefix = codeRule.getPrefix();
        String separator1 = codeRule.getSeparator1();
        String dateRule = codeRule.getDateRule();
        String separator2 = codeRule.getSeparator2();
        String suffix = codeRule.getSuffix();
        Long sequenceLength = codeRule.getSequenceLength();
        String dateStr = null;
        if (S.isNotBlank(dateRule)) {
            dateStr = new SimpleDateFormat(dateRule).format(new Date());
            // 上次更新时间
            LocalDateTime updateTime = codeRule.getUpdateTime();
            LocalDate prev = updateTime.toLocalDate();
            if (prev.isBefore(LocalDate.now())){
                codeRule.setCurrentNum(0);
                codeRule.setUpdateTime(LocalDateTime.now());
            }
        }
        Integer currentNum = codeRule.getCurrentNum();
        String seq = String.format("%0" + sequenceLength + "d", ++currentNum);
        // 流水号递增
        codeRule.setCurrentNum(currentNum);
        return (prefix + separator1 + dateStr + separator2 + seq + suffix).replaceAll("null", "");
    }


}